//增删改查
const mongoose = require("mongoose");

const Material = require("../models/materialModel");

exports.createMaterial = async (req, res) => {
  let newMaterial;
  try {
    const group = await Material.findOne({ category: req.body.category });
    //若category不存在  则重新创建
    if (group == null) {
      newMaterial = await Material.create({
        category: req.body.category,
        types: [
          {
            density: req.body.density,
            type: req.body.type,
          },
        ],
      });
    } else {
      //否则直接在该category下的types push进去
      group.types.push({
        density: req.body.density,
        type: req.body.type,
      });
      newMaterial = await Material.updateOne(
        { category: req.body.category },
        group
      );
    }

    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newMaterial,
    });
  } catch (err) {
    // console.log(req.body);
    res.status(404).json({
      Error: err,
    });
  }
};

exports.getAllMaterial = async (req, res) => {
  try {
    const material = await Material.find();
    // OK 请求成功
    res.status(200).json({
      status: "success",
      message: material,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      Error: err,
    });
  }
};

exports.getMaterialById = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const material = await Material.findOne({ _id: id });
    res.status(200).json({
      status: "success",
      message: material,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      Error: err,
    });
  }
};

exports.updateMaterial = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const data = await Material.updateOne({ _id: id }, req.body);
    res.status(200).json({
      status: "success",
      message: data,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      Error: err,
    });
  }
};

exports.deleteMaterial = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const data = await Material.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      message: data,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      Error: err,
    });
  }
};
